package ru.compft.common.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Repository;
import ru.compft.common.dao.RoleToPermissionDao;
import ru.compft.common.data.AppRoleToPermission;
import ru.compft.common.data.meta.AppRoleToPermissionProperty;

import javax.annotation.Resource;
import java.util.List;

/**
 * User: ASUS
 * Date: 27.10.12
 * Time: 1:09
 */
@Repository
public class RoleToPermissionDaoImpl implements RoleToPermissionDao, InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(RoleToPermissionDaoImpl.class);

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("*RoleToPermissionDaoImpl Autowired sessionFactory {" + sessionFactory + "} *");
    }

    @Override
    public List<AppRoleToPermission> getAllRolesToPermissions() {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Criteria criteria = session.createCriteria(AppRoleToPermission.class);

            return criteria.list();
        } catch (HibernateException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (session != null && session.isOpen()) session.close();
        }
        return null;
    }

    @Override
    public List<AppRoleToPermission> getAllPermissionsByRoleId(Long roleId) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Criteria criteria = session.createCriteria(AppRoleToPermission.class)
                    .add(Restrictions.eq(AppRoleToPermissionProperty.roleId, roleId));

            return criteria.list();
        } catch (HibernateException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (session != null && session.isOpen()) session.close();
        }
        return null;
    }
}
